package wx_article_catcher

import (
	"flag"
	"fmt"
	"os"
	"regexp"
	"strings"
	"time"
	"webDownloader/engine/base"
	"webDownloader/engine/generic"
	"webDownloader/engine/wx_article_catcher/utils"
)

func init() {
	generic.RegisterEngine(&EngineWxArticle{})
}

type EngineWxArticle struct {
	generic.EngineGeneric
}

func (e *EngineWxArticle) Accept(url string) bool {
	return strings.Contains(url, "://mp.weixin.qq.com") &&
		(strings.Contains(url, "/s?__biz=") || strings.Contains(url, "/s/"))
}

func (e *EngineWxArticle) ParseConfig() *map[string]interface{} {
	fmt.Println("正在解析命令行配置...")
	savePath := flag.String("p", "./", "用于指定下载路径，默认为下载到当前工作目录，带空格的路径需要用引号包裹")
	book := flag.Bool("b", false, "用于指定处理成对pandoc友好的格式，方便制作电子书")
	printCss := flag.Bool("css", false, "输出评论区的css样式文件，用于部署静态页面，若没有此文件评论区格式会出错")
	hideDonate := flag.Bool("d", false, "在下载完成后不显示捐助信息，直接退出")
	flag.Parse()
	// 存储路径必须以 "/" 结尾，简化后续处理步骤
	path := *savePath
	if !strings.HasSuffix(path, "/") {
		path += "/"
	}
	e.Conf["savePath"] = path
	e.Conf["book"] = *book
	e.Conf["printCss"] = *printCss
	e.Conf["hideDonate"] = *hideDonate
	SetThreads(1)
	return &e.Conf
}

func (e *EngineWxArticle) ParseDownloadTask() []base.IDownload {
	e.Tasks = make([]base.IDownload, 0)

	_url := e.Conf["refUrl"].(string)

	cookies := map[string]string{}
	e.Conf["cookies"] = cookies

	data := utils.WxRequest(_url, &e.Conf, true)
	titleReg := regexp.MustCompile("<meta property=\"og:title\" content=\"(.*)\" />")
	appMsgTokenReg := regexp.MustCompile("var appmsg_token.*= \"(.*)\";")
	content := string(data)
	submatch := titleReg.FindAllStringSubmatch(content, 1)

	article := &DownloadTaskWxArticle{
		Context: e,
	}
	article.Url = _url
	article.FileName = submatch[0][1]
	article.Date = (time.Now().Unix() / 1000) * 1000
	submatch = appMsgTokenReg.FindAllStringSubmatch(content, 1)
	if len(submatch) > 0 {
		e.Conf["appMsgToken"] = submatch[0][1]
	}
	e.Tasks = append(e.Tasks, article)
	return e.Tasks
}

func (e *EngineWxArticle) SyncDownloadTask() []base.IDownload {
	// 对下载任务进行同步（去掉已完成的任务），在单篇下载器中不做处理
	tasks := make([]base.IDownload, 0)
	for _, task := range e.Tasks {
		article := task.(interface{}).(*DownloadTaskWxArticle)

		// 对文件名进行规范化
		article.FileName = utils.IllegalChar1.ReplaceAllString(article.FileName, "_")
		article.FileName = utils.IllegalChar2.ReplaceAllString(article.FileName, "")

		filePath := e.Conf["savePath"].(string) + article.FileName + ".html"
		fileDesc, _ := os.Stat(filePath)
		if fileDesc != nil {
			fmt.Printf("文章【%s】已存在，判定为已下载，跳过\n", article.FileName)
		}
		tasks = append(tasks, article)
	}
	return tasks
}
